package com.flag.liutao.common.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.flag.liutao.modules.role.vo.MenuDTO;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TreeUtil {

    public static List<MenuDTO> getTree(List<MenuDTO>list,Long pid){
        List<MenuDTO> menuList = new ArrayList<>();
        Iterator<MenuDTO> iterator = list.iterator();
        while (iterator.hasNext()) {
            MenuDTO menu = iterator.next();
            if(menu.getPid()==pid){
                setChilren(list,menu);
                menuList.add(menu);
            }
        }
        return menuList;
    }

    public static void setChilren(List<MenuDTO>list,MenuDTO menuDTO){
        List<MenuDTO> chilrenList = getChilren(list,menuDTO);
        menuDTO.setChilren(chilrenList);
        if(CollectionUtil.isEmpty(chilrenList)){
            menuDTO.setChilren(null);
        }
        Iterator<MenuDTO> iterator = chilrenList.iterator();
        while (iterator.hasNext()) {
            MenuDTO nextChilren = iterator.next();
            setChilren(list,nextChilren);
        }
    }

    private static List<MenuDTO> getChilren(List<MenuDTO> list, MenuDTO menuDTO) {
        List<MenuDTO> chilrenList = new ArrayList<>();
        Iterator<MenuDTO> iterator = list.iterator();
        while (iterator.hasNext()) {
            MenuDTO menu = iterator.next();
            if(menu.getPid()==menuDTO.getValue()){
                chilrenList.add(menu);
            }
        }
        return chilrenList;
    }


}
